package im.oen.boot.api.configure;

import im.oen.boot.api.constant.OenApiConst;
import im.oen.boot.api.servlet.ApiUriDispatcherServlet;
import im.oen.boot.common.utils.Checker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author Kevin.Xu
 */
@Configuration
public class ApiStarterAutoConfigure {

    private Logger log = LoggerFactory.getLogger(ApiStarterAutoConfigure.class);

    @Value("${oen.api.url.prefix:}")
    private String API_URL_PREFIX;

    @Value("${server.servlet.context-path:}")
    private String PRO_URI;


    @Autowired
    private ApplicationContext context;
    @Autowired
    private WebApplicationContext webContext;

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        String prefix = "/oen-api";
        if (Checker.isNotEmpty(API_URL_PREFIX)) {
            prefix = API_URL_PREFIX;
        }
        String proUri = "";
        if (Checker.isNotEmpty(PRO_URI) && !"/".equalsIgnoreCase(PRO_URI)) {
            proUri = PRO_URI;
        }
        OenApiConst.instance(proUri, prefix);

        ApiUriDispatcherServlet apiDispatcherServlet = new ApiUriDispatcherServlet(webContext, context);
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(apiDispatcherServlet, "/*");
        registrationBean.setLoadOnStartup(1);
        registrationBean.setAsyncSupported(true);
        registrationBean.setName("oen-api");
        return registrationBean;
    }
}
